import { message, Card, Layout, Table, Button, Space, Typography, Tag, Spin, Row, Col, Divider } from "antd";
import {
    ReloadOutlined,
    CloudOutlined,
    ClusterOutlined,
    GroupOutlined,
    CheckCircleOutlined,
    ClockCircleOutlined,
    DockerOutlined
} from "@ant-design/icons";
import RequestUtils from "../../utils/RequestUtils";
import Apis from "../../configs/Apis";
import { useEffect, useState } from "react";

const { Header, Content } = Layout;
const { Title, Text } = Typography;

const ServiceInstance = () => {
    const [messageApi, contextHolder] = message.useMessage();
    const [serviceInstances, setServiceInstances] = useState([]);
    const [loading, setLoading] = useState(false);
    const [lastRefreshTime, setLastRefreshTime] = useState(null);
    const [refreshTimer, setRefreshTimer] = useState(null);

    // 组件挂载时初始化并设置定时器
    useEffect(() => {
        // 初始加载数据
        doSearchServiceInstance();

        // 设置10秒自动刷新
        const timer = setInterval(doSearchServiceInstance, 10000);
        setRefreshTimer(timer);

        // 组件卸载时清除定时器
        return () => clearInterval(timer);
    }, []);

    /**
     * 查询所有在线服务实例
     */
    const doSearchServiceInstance = () => {
        setLoading(true);
        RequestUtils.post(Apis.Nacos.pageQueryServiceInstance, {
            pageNum: 1,
            pageSize: 1000
        }).then(res => {
            setServiceInstances(res.records);
            setLastRefreshTime(new Date());
            setLoading(false);
        }).catch(err => {
            messageApi.error("查询服务实例失败, " + err.message);
            setLoading(false);
        })
    }

    // 手动刷新
    const handleManualRefresh = () => {
        // 清除现有定时器并重新设置，避免刷新重叠
        if (refreshTimer) {
            clearInterval(refreshTimer);
        }
        doSearchServiceInstance();
        messageApi.success("刷新服务实例...");
        const newTimer = setInterval(doSearchServiceInstance, 10000);
        setRefreshTimer(newTimer);
    }

    // 表格列定义
    const columns = [
        {
            title: '服务名',
            dataIndex: 'serviceName',
            key: 'serviceName',
            render: (text) => <Text strong>{text}</Text>,
            sorter: (a, b) => a.serviceName.localeCompare(b.serviceName),
        },
        {
            title: '分组名称',
            dataIndex: 'groupName',
            key: 'groupName',
            render: (text) => <Tag color="blue">{text}</Tag>,
        },
        {
            title: '集群数量',
            dataIndex: 'clusterCount',
            key: 'clusterCount',
            render: (count) => (
                <Space>
                    <ClusterOutlined style={{ color: '#2f54eb' }} />
                    <Text>{count}</Text>
                </Space>
            ),
            sorter: (a, b) => a.clusterCount - b.clusterCount,
        },
        {
            title: '健康实例数',
            dataIndex: 'healthyInstanceCount',
            key: 'healthyInstanceCount',
            render: (count) => (
                <Space>
                    <CheckCircleOutlined style={{ color: '#52c41a' }} />
                    <Text>{count}</Text>
                </Space>
            ),
            sorter: (a, b) => a.healthyInstanceCount - b.healthyInstanceCount,
        },
    ];

    return (
        <Layout style={{ minHeight: '100%' }}>
            {contextHolder}

            <Header style={{
                background: '#fff',
                padding: '0 20px',
                boxShadow: '0 2px 8px rgba(0, 0, 0, 0.08)',
                position: 'sticky',
                top: 0,
                zIndex: 1
            }}>
                <Row justify="space-between" align="middle" style={{ height: '100%' }}>
                    <Col>
                        <Title level={4} style={{ margin: 0 }}>
                            <DockerOutlined style={{ marginRight: 8, color: '#1890ff' }} />
                            服务实例管理
                        </Title>
                    </Col>
                    <Col>
                        <Space>
                            <Button
                                icon={<ReloadOutlined />}
                                onClick={handleManualRefresh}
                                loading={loading}
                                type="primary"
                                size="middle"
                            >
                                手动刷新
                            </Button>
                            {lastRefreshTime && (
                                <Text type="secondary">
                                    <ClockCircleOutlined style={{ fontSize: 12, marginRight: 4 }} />
                                    最后刷新: {lastRefreshTime.toLocaleTimeString()}
                                </Text>
                            )}
                        </Space>
                    </Col>
                </Row>
            </Header>

            <Content style={{ padding: '20px' }}>
                <Card
                    title="在线服务实例列表"
                    bordered={false}
                    style={{
                        background: '#fff',
                        borderRadius: 8,
                        boxShadow: '0 4px 12px rgba(0, 0, 0, 0.05)',
                        transition: 'all 0.3s'
                    }}
                    hoverable
                    extra={
                        <Text type="secondary" style={{ fontSize: 13 }}>
                            系统将每10秒自动刷新一次 · 共 {serviceInstances.length} 个服务实例
                        </Text>
                    }
                >
                    <Spin spinning={loading} tip="加载服务实例中...">
                        {serviceInstances.length > 0 ? (
                            <Table
                                columns={columns}
                                dataSource={serviceInstances.map((item, index) => ({
                                    ...item,
                                    key: index,
                                }))}
                                pagination={false}  // 禁用分页控件
                                rowHover
                                scroll={{ x: 'max-content' }}
                                style={{
                                    transition: 'all 0.3s ease',
                                }}
                                locale={{ emptyText: '暂无服务实例数据' }}
                            />
                        ) : (
                            <div style={{
                                textAlign: 'center',
                                padding: '60px 0',
                                background: '#fafafa',
                                borderRadius: 4,
                                border: '1px dashed #e8e8e8'
                            }}>
                                <CloudOutlined style={{ fontSize: 48, color: '#ccc', marginBottom: 16 }} />
                                <p style={{ color: '#666', fontSize: 16 }}>当前没有在线的服务实例</p>
                                <Button
                                    icon={<ReloadOutlined />}
                                    onClick={handleManualRefresh}
                                    style={{ marginTop: 16 }}
                                >
                                    尝试重新加载
                                </Button>
                            </div>
                        )}
                    </Spin>
                </Card>
            </Content>
        </Layout>
    )
}

export default ServiceInstance;
